//
//  NetWorkRequestApi.m
//  BaoGongBao
//
//  Created by User on 14/11/16.
//  Copyright (c) 2014年 irule. All rights reserved.
//

#import "NetWorkRequestApi.h"

@implementation NetWorkRequestApi
static NetWorkRequestApi *_sharedNetWorkRequestApi = nil;

+ (NetWorkRequestApi *)sharedNetWorkRequestApi
{
	if (!_sharedNetWorkRequestApi)
	{
		_sharedNetWorkRequestApi = [[self alloc] init];
	}

	return _sharedNetWorkRequestApi;
}

- (instancetype)init
{
    self = [super init];
    if (self)
    {

    }
    return self;
}

#pragma mark - 检测网络连接
- (void)reach
{
	/**
	 AFNetworkReachabilityStatusUnknown          = -1,  // 未知
	 AFNetworkReachabilityStatusNotReachable     = 0,   // 无连接
	 AFNetworkReachabilityStatusReachableViaWWAN = 1,   // 3G 花钱
	 AFNetworkReachabilityStatusReachableViaWiFi = 2,   // 局域网络,不花钱
	 */
	// 如果要检测网络状态的变化,必须用检测管理器的单例的startMonitoring
	[[AFNetworkReachabilityManager sharedManager] startMonitoring];

	// 检测网络连接的单例,网络变化时的回调方法
	[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
		NSLog(@"%d", status);
		switch (status)
		{
			case AFNetworkReachabilityStatusUnknown:
			{
				[[iToast makeText:kNRStr_NetworkStatusUnknown] show];
			}
				break;

			case AFNetworkReachabilityStatusNotReachable:
			{
				[[iToast makeText:kNRStr_NetworkStatusNotReachable] show];
			}
				break;

			case AFNetworkReachabilityStatusReachableViaWWAN:
			{
				[[iToast makeText:kNRStr_NetworkStatusReachableViaWWAN] show];
			}
				break;

			case AFNetworkReachabilityStatusReachableViaWiFi:
			{
				[[iToast makeText:kNRStr_NetworkStatusReachableViaWiFi] show];
			}
				break;

			default:
			{
				[[iToast makeText:kNRStr_NetworkStatusDefault] show];
			}
				break;
				
		}
	}];
}

#pragma mark - Session 下载
- (void)sessionDownload
{
	NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
	AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:config];

	NSString *urlString = @"http://localhost/itcast/videos/01.C语言-语法预览.mp4";
	urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

	NSURL *url = [NSURL URLWithString:urlString];
	NSURLRequest *request = [NSURLRequest requestWithURL:url];

	NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
		// 指定下载文件保存的路径
		//        NSLog(@"%@ %@", targetPath, response.suggestedFilename);
		// 将下载文件保存在缓存路径中
		NSString *cacheDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
		NSString *path = [cacheDir stringByAppendingPathComponent:response.suggestedFilename];

		// URLWithString返回的是网络的URL,如果使用本地URL,需要注意
		NSURL *fileURL1 = [NSURL URLWithString:path];
		NSURL *fileURL = [NSURL fileURLWithPath:path];

		NSLog(@"== %@ |||| %@", fileURL1, fileURL);

		return fileURL;
	} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
		NSLog(@"%@ %@", filePath, error);
	}];

	[task resume];
}

#pragma mark - POST JSON
- (void)postJSON
{
	AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

	NSDictionary *dict = @{@"name": @"zhangsan"};
	NSDictionary *dict1 = @{@"name": @"wangwu"};
	NSArray *array = @[dict, dict1];
	// 设置请求格式
	manager.requestSerializer = [AFJSONRequestSerializer serializer];
	// 设置返回格式
	manager.responseSerializer = [AFHTTPResponseSerializer serializer];

	[manager POST:@"http://localhost/postjson.php" parameters:array success:^(AFHTTPRequestOperation *operation, id responseObject) {
		NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

		NSLog(@"%@", result);
	} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

	}];

}

#pragma mark - 随机文件名上传
- (void)postUpload1
{
	// 本地上传给服务器时,没有确定的URL,不好用MD5的方式处理
	AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
	manager.responseSerializer = [AFHTTPResponseSerializer serializer];

	[manager POST:@"http://localhost/demo/upload.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

		NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"头像1.png" withExtension:nil];

		// 要上传保存在服务器中的名称
		// 使用时间来作为文件名 2014-04-30 14:20:57.png
		// 让不同的用户信息,保存在不同目录中
		NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
		// 设置日期格式
		formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
		NSString *fileName = [formatter stringFromDate:[NSDate date]];

		[formData appendPartWithFileURL:fileURL name:@"uploadFile" fileName:fileName mimeType:@"image/png" error:NULL];

	} success:^(AFHTTPRequestOperation *operation, id responseObject) {
		NSLog(@"OK");
	} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
		NSLog(@"error");
	}];
}

#pragma mark - POST上传
- (void)postUpload
{
	AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
	// AFHTTPResponseSerializer就是正常的HTTP请求响应结果:NSData
	// 当请求的返回数据不是JSON,XML,PList,UIImage之外,使用AFHTTPResponseSerializer
	// 例如返回一个html,text...
	//
	// 实际上就是AFN没有对响应数据做任何处理的情况
	manager.responseSerializer = [AFHTTPResponseSerializer serializer];

	// formData是遵守了AFMultipartFormData的对象
	[manager POST:@"http://localhost/demo/upload.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

		// 将本地的文件上传至服务器
		NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"头像1.png" withExtension:nil];

		[formData appendPartWithFileURL:fileURL name:@"uploadFile" error:NULL];
	} success:^(AFHTTPRequestOperation *operation, id responseObject) {
		NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

		NSLog(@"完成 %@", result);
	} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
		NSLog(@"错误 %@", error.localizedDescription);
	}];
}

#pragma mark - JSON
- (void)XMLData
{
	AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

	// 返回的数据格式是XML
	manager.responseSerializer = [AFXMLParserResponseSerializer serializer];

	NSDictionary *dict = @{@"format": @"xml"};

	// 网络访问是异步的,回调是主线程的,因此程序员不用管在主线程更新UI的事情
	[manager GET:@"http://localhost/videos.php" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {

		// 如果结果是XML,同样需要使用6个代理方法解析,或者使用第三方库
		// 第三方库第三方框架,效率低,内存泄漏
		NSLog(@"%@", responseObject);
	} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
		NSLog(@"%@", error);
	}];
}

#pragma mark - JSON
- (void)JSONData
{
	AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

	// 原本需要拼接get访问URL ? & =
	NSDictionary *dict = @{@"format": @"json"};

	// 网络访问是异步的,回调是主线程的,因此程序员不用管在主线程更新UI的事情
	[manager GET:@"http://localhost/videos.php" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
		NSLog(@"%@", responseObject);
		// 提问:NSURLConnection异步方法回调,是在子线程
		// 得到回调之后,通常更新UI,是在主线程
		NSLog(@"%@", [NSThread currentThread]);
	} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
		NSLog(@"%@", error);
	}];
}

#pragma mark - POST登录
- (void)postLogin
{
	AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

	// 原本需要拼接get访问URL ? & =
	NSDictionary *dict = @{@"username": @"wangwu", @"password" : @"wang"};

	// 网络访问是异步的,回调是主线程的,因此程序员不用管在主线程更新UI的事情
	[manager POST:@"http://localhost/login.php" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
		NSLog(@"%@", responseObject);
		// 提问:NSURLConnection异步方法回调,是在子线程
		// 得到回调之后,通常更新UI,是在主线程
		NSLog(@"%@", [NSThread currentThread]);
	} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
		NSLog(@"%@", error);
	}];
}



#pragma mark - GET登录
- (void)getLogin
{
	AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

	// 原本需要拼接get访问URL ? & =
	NSDictionary *dict = @{@"username": @"wangwu", @"password" : @"wang"};

	// 网络访问是异步的,回调是主线程的,因此程序员不用管在主线程更新UI的事情
	[manager GET:@"http://localhost/login.php" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
		NSLog(@"%@", responseObject);
		// 提问:NSURLConnection异步方法回调,是在子线程
		// 得到回调之后,通常更新UI,是在主线程
		NSLog(@"%@", [NSThread currentThread]);
	} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
		NSLog(@"%@", error);
	}];
}

#pragma mark - GetVersion
//http://220.178.74.185:17777/api/App/GetVersion?appId=HMP_002&platform=3
- (void)nrGetVersion:(NSDictionary *)parameters
			 success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
			 failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
	AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
	[manager GET:[NSString stringWithFormat:@"%@/api/App/%@?", kURLmain, kURL_CheckApiStatus] parameters:parameters success:success
		 failure:failure];
}

#pragma mark - CheckApiStatus
//http://220.178.74.185:17777/api/CheckApiStatus?appId=HMP_002
- (void)nrCheckApiStatus:(NSDictionary *)parameters
				 success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
				 failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{

	AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
	[manager GET:[NSString stringWithFormat:@"%@/api/%@?", kURLmain, kURL_CheckApiStatus] parameters:parameters success:success
		 failure:failure];
}

#pragma mark - Login
//http://220.178.74.185:17777/api/Login appid:HMP_002   deviceid:860955020541003   userName:
- (void)nrLogin:(NSDictionary *)parameters
		success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
		failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{

	AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
	[manager POST:[NSString stringWithFormat:@"%@/api/%@?", kURLmain, kURL_Login] parameters:parameters success:success
		 failure:failure];
}

#pragma mark - Register
//http://220.178.74.185:17777/api/Register
//-->param:{PlatForm=3, mobilenum=15256995851, appid=HMP_001, DeviceName=MI 2S, OSName=android 4.1.1, loginplace=中国,安徽省,合肥市,蜀山区,创业大道,117.201456,31.861073, deviceid=860955020541003}
- (void)nrRegister:(NSDictionary *)parameters
		success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
		failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{

	AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
	[manager POST:[NSString stringWithFormat:@"%@/api/%@?", kURLmain, kURL_Register] parameters:parameters success:success
		  failure:failure];
}



#pragma mark - RegisterNext
//http://220.178.74.185:17777/api/Register
//-->param:{PlatForm=3, mobilenum=15256995851, appid=HMP_001, DeviceName=MI 2S, OSName=android 4.1.1, loginplace=中国,安徽省,合肥市,蜀山区,创业大道,117.201456,31.861073, deviceid=860955020541003}
- (void)RegisterNext:(NSDictionary *)parameters
		   success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
		   failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{

	AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
	[manager POST:[NSString stringWithFormat:@"%@/api/%@?", kURLmain, @"RegisterNext"] parameters:parameters success:success
		  failure:failure];
}

#pragma mark 个人信息
//http://220.178.74.185:17777/hmp_002/api/GetMesUserInfo?UserName=zhangzenghui&token=ee820e2f8bc444088d696401ff65b3f9
- (void)nrGetMesUserInfo:(NSDictionary *)parameters
				 success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
				 failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{

	AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

	// 原本需要拼接get访问URL ? & =
	//	NSDictionary *dict = @{@"username": @"wangwu", @"password" : @"wang"};

	// 网络访问是异步的,回调是主线程的,因此程序员不用管在主线程更新UI的事情
	[manager GET:[NSString stringWithFormat:@"%@/hmp_002/api/%@?", kURLmain, kURL_GetMesUserInfo] parameters:parameters success:success//^(AFHTTPRequestOperation *operation, id responseObject) {
	 //		NSLog(@"%@", responseObject);
		// 提问:NSURLConnection异步方法回调,是在子线程
		// 得到回调之后,通常更新UI,是在主线程
	 //		NSLog(@"%@", [NSThread currentThread]);
	 //	}
		 failure:failure//^(AFHTTPRequestOperation *operation, NSError *error) {
	 //		NSLog(@"%@", error);
	 //	}
	 ];
	
}


#pragma mark 零部件报工 完工报工
//http://220.178.74.185:17777/hmp_002/api/GetPartInfo?AUFNR=44555&VORNR=0010&Token=4a94059b759e4d9fa0bc62e4bb764cb0
- (void)SparePartsWangGongBaoGongSearch:(NSDictionary *)parameters
								success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
								failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
	AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

	// 原本需要拼接get访问URL ? & =
//	NSDictionary *dict = @{@"username": @"wangwu", @"password" : @"wang"};

	// 网络访问是异步的,回调是主线程的,因此程序员不用管在主线程更新UI的事情
	[manager GET:[NSString stringWithFormat:@"%@/hmp_002/api/%@?", kURLmain, kURL_GetPartInfo] parameters:parameters success:success failure:failure];

}

#pragma mark SearchPartWork
//url:http://220.178.74.185:17777/hmp_002/api/SearchPartWork?Token=deb7709020ae422b9bebeab54d822cb2   searchParas:{"ISSUCCESS":"E","EDATE":"","AUFNR":"","BDATE":""}
- (void)SearchPartWork:(NSDictionary *)parameters
				  success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
				  failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
	AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
	// 原本需要拼接get访问URL ? & =
	//	NSDictionary *dict = @{@"username": @"wangwu", @"password" : @"wang"};

	// 网络访问是异步的,回调是主线程的,因此程序员不用管在主线程更新UI的事情
	[manager POST:[NSString stringWithFormat:@"%@/hmp_002/api/%@?Token=%@", kURLmain, kURL_SearchPartWork, gToken] parameters:parameters success:success failure:failure];
}

#pragma mark SearchForkmanWork
//http://220.178.74.185:17777/hmp_002/api/SearchForkmanWork?Token=f2b6ea1ece0a47748fc00bd228b21b78   searchParas:{"ISSUCCESS":"E","EDATE":"","AUFNR":"","BDATE":""}
- (void)SearchForkmanWork:(NSDictionary *)parameters
				  success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
				  failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
	AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

	// 原本需要拼接get访问URL ? & =
	//	NSDictionary *dict = @{@"username": @"wangwu", @"password" : @"wang"};

	// 网络访问是异步的,回调是主线程的,因此程序员不用管在主线程更新UI的事情
	[manager POST:[NSString stringWithFormat:@"%@/hmp_002/api/%@?Token=%@", kURLmain, kURL_SearchForkmanWork, gToken] parameters:parameters success:success failure:failure];

}


#pragma mark GetPartInfo
//ht tp://220.178.74.185:17777/hmp_002/api/GetPartInfo?AUFNR=007200038879&VORNR=0010&Token=4a271207b3fd4b6db46251d502da99b9
- (void)GetPartInfo:(NSDictionary *)parameters
				  success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
				  failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
	AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

	// 原本需要拼接get访问URL ? & =
	//	NSDictionary *dict = @{@"username": @"wangwu", @"password" : @"wang"};

	// 网络访问是异步的,回调是主线程的,因此程序员不用管在主线程更新UI的事情
	[manager GET:[NSString stringWithFormat:@"%@/hmp_002/api/GetPartInfo?Token=%@", kURLmain, gToken] parameters:parameters success:success failure:failure];
	
}

#pragma mark SavePartWork
//url:ht tp://220.178.74.185:17777/hmp_002/api/SavePartWork?Token=  center:0010  bg:10
// us:zhangzenghui maH97Y5-22001  token:828c870b2f4d4fe5ad1dbe301d8683bf
- (void)SavePartWork:(NSDictionary *)parameters
			success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
			failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
	AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

	// 原本需要拼接get访问URL ? & =
	//	NSDictionary *dict = @{@"username": @"wangwu", @"password" : @"wang"};

	// 网络访问是异步的,回调是主线程的,因此程序员不用管在主线程更新UI的事情
	[manager POST:[NSString stringWithFormat:@"%@/hmp_002/api/SavePartWork?Token=%@", kURLmain, gToken] parameters:parameters success:success failure:failure];

}

#pragma mark GetForkmanInfo
//ht tp://220.178.74.185:17777/hmp_002/api/GetForkmanInfo?AUFNR=007200038879&VORNR=0010&Token=915a611f12794ba1973243d643b46dd1
- (void)GetForkmanInfo:(NSDictionary *)parameters
			 success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
			 failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
	AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
	[manager GET:[NSString stringWithFormat:@"%@/hmp_002/api/GetForkmanInfo?Token=%@", kURLmain, gToken] parameters:parameters success:success failure:failure];
	
}

#pragma mark SyncPartWork
- (void)SyncPartWork:(NSDictionary *)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
	AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

	[manager POST:[NSString stringWithFormat:@"%@/hmp_002/api/SyncPartWork?Token=%@", kURLmain, gToken] parameters:parameters success:success failure:failure];

}

#pragma mark SyncForkmanWork
//ht tp://220.178.74.185:17777/hmp_002/api/SyncForkmanWork?Token=a33701fc9fc345ef9eea6a835ef24d74
- (void)SyncForkmanWork:(NSDictionary *)parameters
			   success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
			   failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
	AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

	[manager POST:[NSString stringWithFormat:@"%@/hmp_002/api/SyncForkmanWork?Token=%@", kURLmain, gToken] parameters:parameters success:success failure:failure];
	
}


@end
